package org.hepeng.workx.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.service.error.Error;
import org.springframework.http.HttpStatus;

/**
 * @author he peng
 */

@JsonIgnoreProperties({"error" , "data" , "success" , "httpStatus"})
@JsonPropertyOrder({"code" , "msg" , "token" , "entity"})
@Getter
public class RestServiceCallResult<E extends Error,D extends Object> extends CommonServiceCallResult {

    private Integer code;
    private String token;
    private Object entity;
    private HttpStatus httpStatus;

    public static RestServiceCallResultBuilder restBuilder() {
        return new RestServiceCallResultBuilder();
    }

    public static class RestServiceCallResultBuilder<E extends Error,D extends Object> {

        private RestServiceCallResult restServiceCallResult = new RestServiceCallResult();

        public RestServiceCallResultBuilder code(Integer errorCode) {
            restServiceCallResult.code = errorCode;
            return this;
        }

        public RestServiceCallResultBuilder msg(String errorMsg) {
            restServiceCallResult.msg = errorMsg;
            return this;
        }

        public RestServiceCallResultBuilder token(String token) {
            restServiceCallResult.token = token;
            return this;
        }

        public RestServiceCallResultBuilder entity(Object entity) {
            restServiceCallResult.entity = entity;
            return this;
        }

        public RestServiceCallResultBuilder httpStatus(HttpStatus httpStatus) {
            restServiceCallResult.httpStatus = httpStatus;
            return this;
        }

        public RestServiceCallResultBuilder serviceCallResult(ServiceCallResult scr) {
            restServiceCallResult.error = scr.getError();
            restServiceCallResult.data = scr.getData();
            code(scr.getError().getCode());
            msg(scr.getMsg());
            entity(scr.getData());
            return this;
        }

        public RestServiceCallResultBuilder error(E error) {
            restServiceCallResult.error = error;
            code(error.getCode());
            if (StringUtils.isBlank(restServiceCallResult.msg)) {
                msg(error.getMsg());
            }
            return this;
        }

        public RestServiceCallResultBuilder data(D data) {
            restServiceCallResult.data = data;
            entity(data);
            return this;
        }

        public RestServiceCallResult build() {
            return restServiceCallResult;
        }
    }

}
